//
//  ApproveViewController.m
//  cm
//
//  Created by suyibaishan on 2017/11/7.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "ApproveViewController.h"
#import "AuditViewController.h"
#import "JoinViewController.h"
#import "ApproveCell.h"
#import "MRProgressOverlayView+AFNetworking.h"

@interface ApproveViewController () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UITableView *_tableView;
    UIView *headView;
    UIView *footView;
    NSArray *titleArr;
    NSArray *holderArr;
    NSString *name;
    NSString *card;
    NSString *address;
    UIButton *facadeBtn;
    UIButton *reverseBtn;
    BOOL isCamera;
    NSString *urlType;
    NSString *facadeUrl;
    NSString *reverseUrl;
}
@end

@implementation ApproveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createApplyView];
}

-(void)createApplyView
{
    self.titleLabel.text = @"信息认证";
    self.backButton.hidden = NO;
    
    titleArr = @[@"用户账号",@"真实姓名*",@"身份证号码*",@"家庭住址(选填)"];
    holderArr = @[@"",@"请输入姓名",@"请输入身份证号码",@"请输入家庭住址"];
    
    [self createHeadView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.baseBarHeight, kScreenWidth, kScreenHeight - self.baseBarHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = headView;
    
    [self createFootView];
    _tableView.tableFooterView = footView;
}

-(void)createHeadView
{
    headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90)];
    
    UILabel *welcomeLabel = [[UILabel alloc] init];
    welcomeLabel.layer.cornerRadius = 12.5;
    welcomeLabel.clipsToBounds = YES;
    welcomeLabel.textAlignment = NSTextAlignmentCenter;
    welcomeLabel.font = [UIFont systemFontOfSize:14];
    welcomeLabel.text = [NSString stringWithFormat:@"•欢迎加入"];
    welcomeLabel.textColor = [UIColor whiteColor];
    welcomeLabel.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [headView addSubview:welcomeLabel];
    welcomeLabel.sd_layout
    .topSpaceToView(headView, 35)
    .leftSpaceToView(headView, 20)
    .widthIs(75)
    .heightIs(25);
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [headView addSubview:line];
    line.sd_layout
    .leftSpaceToView(welcomeLabel, 0)
    .topSpaceToView(headView, 47.5)
    .widthIs(kScreenWidth - 115)
    .heightIs(0.5);
    
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.textAlignment = NSTextAlignmentRight;
    timeLabel.font = [UIFont systemFontOfSize:12];
    timeLabel.text = @"加入时间:2017/11/1";
    timeLabel.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1];
    [headView addSubview:timeLabel];
    timeLabel.sd_layout
    .topSpaceToView(line, 0)
    .rightSpaceToView(headView, 30)
    .widthIs(kScreenWidth/2)
    .heightIs(15);
    
    UILabel *remarkLabel = [[UILabel alloc] init];
    remarkLabel.textAlignment = NSTextAlignmentRight;
    remarkLabel.font = [UIFont systemFontOfSize:12];
    remarkLabel.text = @"带“ * ”的为必填项目";
    remarkLabel.textColor = [UIColor blackColor];
    [headView addSubview:remarkLabel];
    remarkLabel.sd_layout
    .topSpaceToView(timeLabel, 5)
    .rightSpaceToView(headView, 30)
    .widthIs(kScreenWidth/2)
    .heightIs(15);
}

-(void)createFootView
{
    footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 230)];
    
    UIView *identityView = [[UIView alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth-40, 120)];
    identityView.layer.borderWidth = 0.5;
    identityView.layer.borderColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1].CGColor;
    [footView addSubview:identityView];
    
    for (NSInteger i = 0; i < 2; i++) {
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:14];
        label.text = i == 0?@"身份证正面*":@"身份证反面*";
        label.textColor = [UIColor blackColor];
        [identityView addSubview:label];
        label.sd_layout
        .topSpaceToView(identityView, 0)
        .leftSpaceToView(identityView, 10+i*(kScreenWidth-50)/2)
        .widthIs((kScreenWidth-50)/2)
        .heightIs(40);
    }
    
    facadeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [facadeBtn setImage:[UIImage imageNamed:@"cm_plus"] forState:UIControlStateNormal];
    [facadeBtn addTarget:self action:@selector(facadeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [identityView addSubview:facadeBtn];
    facadeBtn.sd_layout
    .leftSpaceToView(identityView, 0)
    .topSpaceToView(identityView, 40)
    .widthIs((kScreenWidth-40)/2)
    .heightIs(80);
    
    reverseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [reverseBtn setImage:[UIImage imageNamed:@"cm_plus"] forState:UIControlStateNormal];
    [reverseBtn addTarget:self action:@selector(reverseBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [identityView addSubview:reverseBtn];
    reverseBtn.sd_layout
    .leftSpaceToView(identityView, (kScreenWidth-40)/2)
    .topSpaceToView(identityView, 40)
    .widthIs((kScreenWidth-40)/2)
    .heightIs(80);
    
    UIView *thinline = [[UIView alloc] init];
    thinline.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [identityView addSubview:thinline];
    thinline.sd_layout
    .leftSpaceToView(identityView, (kScreenWidth-40)/2)
    .topSpaceToView(identityView, 40)
    .widthIs(0.5)
    .heightIs(80);
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [identityView addSubview:line];
    line.sd_layout
    .leftSpaceToView(identityView, 0)
    .topSpaceToView(identityView, 40)
    .widthIs(kScreenWidth - 40)
    .heightIs(0.5);
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    confirmBtn.layer.cornerRadius = 20;
    confirmBtn.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"提交认证" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [confirmBtn addTarget:self action:@selector(confirmBtnHandler) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:confirmBtn];
    confirmBtn.sd_layout
    .leftSpaceToView(footView, 30)
    .topSpaceToView(identityView, 30)
    .widthIs(kScreenWidth - 60)
    .heightIs(40);
}

-(void)facadeBtnClick
{
    urlType = @"facade";
    [self uploadPhotos];
}

-(void)reverseBtnClick
{
    urlType = @"reverse";
    [self uploadPhotos];
}

-(void)uploadPhotos
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self profileFromCamBtnPressed];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self profileFromPhotoBtnPressed];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)confirmBtnHandler
{
    [self.view endEditing:YES];
    
    if (![self validateIdentityCard:card]) {
        [self showMessage:@"亲，请输入正确的身份证号码"];
        return;
    }
    if (facadeUrl == nil || reverseUrl == nil) {
        [self showMessage:@"亲，请上传完整身份证照片"];
        return;
    }

    [[ToolNet sharedManager] applyForMember:self.userCode card:card frontCardImg:facadeUrl backCardImg:reverseUrl address:address realName:name url:MMemberCheck completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            if ([self.type isEqualToString:@"5"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"CANCELLOGIN" object:nil];
            }
            else {
                JoinViewController *joinVC = [[JoinViewController alloc] init];
                joinVC.userCode = responseJson[@"data"][@"userCode"];
                [self.navigationController pushViewController:joinVC animated:YES];
                [TSMessage showMessage:responseJson[@"msg"] type:TSMessageNotificationTypeSuccess];
            }
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
    }];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    ApproveCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[ApproveCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleLabel.text = titleArr[indexPath.row];
    cell.contentField.delegate = self;
    cell.contentField.placeholder = holderArr[indexPath.row];
    
    if (indexPath.row == 0) {
        cell.contentField.text = self.account;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

#pragma - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    ApproveCell *cell = (ApproveCell *)[[[textField superview] superview] superview];
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    if (indexPath.row == 1){
        name = textField.text;
    }
    else if (indexPath.row == 2){
        card = textField.text;
    }
    else if (indexPath.row == 3){
        address = textField.text;
    }
    [textField resignFirstResponder];
}

#pragma mark - UITextField Delegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    ApproveCell *cell = (ApproveCell *)[[[textField superview] superview] superview];
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    if (indexPath.row == 1){
        name = textField.text;
    }
    else if (indexPath.row == 2){
        card = textField.text;
    }
    else if (indexPath.row == 3){
        address = textField.text;
    }
    [textField resignFirstResponder];
    
    return YES;
}

//身份证号
- (BOOL)validateIdentityCard:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

#pragma mark - Photo & Camera
- (void)profileFromCamBtnPressed
{
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
        isCamera = YES;
    }
}

- (void)profileFromPhotoBtnPressed
{
    // 从相册中选取
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
        isCamera = NO;
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    MRProgressOverlayView *overlayView = [MRProgressOverlayView showOverlayAddedTo:self.view title:@"上传中..." mode:MRProgressOverlayViewModeIndeterminateSmallDefault animated:YES];
    [overlayView setTintColor:UIResourceMainColor];
    if (isCamera) {
        if ([[AFNetworkReachabilityManager sharedManager] isReachable])
        {
            [[ToolNet sharedManager] uploadImage:image completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                [overlayView dismiss:YES];
                if ([responseObject[@"code"] isEqual:@1]) {
                    if ([urlType isEqualToString:@"facade"]) {
//                        [facadeBtn sd_setImageWithURL:[NSURL URLWithString:[kIMGURL stringByAppendingString:responseObject[@"data"]]] forState:UIControlStateNormal];
                        [facadeBtn setImage:image forState:UIControlStateNormal];
                        facadeUrl = responseObject[@"data"];
                    }
                    else if ([urlType isEqualToString:@"reverse"]) {
                        [reverseBtn setImage:image forState:UIControlStateNormal];
                        reverseUrl = responseObject[@"data"];
                    }
                }
                else {
                    [self showMessage:responseObject[@"msg"]];
                }
            }];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [[ToolNet sharedManager] uploadImage:image completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            [overlayView dismiss:YES];
            if ([responseObject[@"code"] isEqual:@1]) {
                if ([urlType isEqualToString:@"facade"]) {
                    [facadeBtn setImage:image forState:UIControlStateNormal];
                    facadeUrl = responseObject[@"data"];
                }
                else if ([urlType isEqualToString:@"reverse"]) {
                    [reverseBtn setImage:image forState:UIControlStateNormal];
                    reverseUrl = responseObject[@"data"];
                }
            }
            else {
                [self showMessage:responseObject[@"msg"]];
            }
        }];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
